package com.haois.mp.wechat.task;

import com.haois.mp.database.commom.constant.Reply;
import com.haois.mp.database.module.offaccounts.service.RemindVehicleService;
import com.haois.mp.database.module.offaccounts.service.VehicleService;
import com.haois.mp.database.module.sdk.api.DriverInfoServer;
import com.haois.mp.database.module.common.daomain.Driver;
import com.haois.mp.database.module.common.daomain.Vehicle;
import com.haois.mp.database.module.wxserver.util.VehicleUtil;
import com.haois.mp.database.util.jx.DateUtil;
import com.haois.mp.wechat.constants.Enum.MenuEnum;
import com.haois.mp.wechat.util.WxUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * description
 *
 * @author RuiHaoZ on GuangZhou
 * @date 2018/9/2 19:57
 */
@Component
public class VehiclePeccancyTask {

    @Value("${defined.wxmp.base-url}")
    private String baseUrl;

    @Autowired
    private VehicleService vehicleService;
    @Autowired
    private RemindVehicleService remindVehicleService;

    Map<String, Object> params = new HashMap<>();
    private Logger logger = LoggerFactory.getLogger(VehiclePeccancyTask.class);

    /**
     * 每月1号和15号更新违章记录 推送给关注用户，并更新入数据库
     *
     * @return 推送次数
     */
    @Scheduled(cron = "0 0 9 15 * ?")
    public Map<String, Object> vehiclePeccancyFalse() {
        logger.info("定时任务【每月1号和15号查看违章记录】触发或手动触发");
        int pushSize = remindVehicleService.vehiclePeccancy(false);
        params.put("pushSize", String.valueOf(pushSize));
        params.put("accordSize", "xxx");
        return params;
    }

    @Scheduled(cron = "0 0 9 1 * ?")
    public Map<String, Object> vehiclePeccancyTrue() {
        logger.info("定时任务【每月1号和15号查看违章记录】触发或手动触发");
        int pushSize = remindVehicleService.vehiclePeccancy(true);
        params.put("pushSize", String.valueOf(pushSize));
        params.put("accordSize", "xxx");
        return params;
    }

    /**
     * 驾照分数清零提醒
     *
     * @return
     */
    @Scheduled(cron = "0 0 9 * * ?")
    public Map<String, Object> driverPeriodRemind() {
        AtomicInteger pushSize = new AtomicInteger();
        AtomicInteger accordSize = new AtomicInteger();
        logger.info("定时任务【每天早上9点检查是否存在30天或7天清零的驾照】触发");
        List<Driver> drivers = vehicleService.findDriver(null);
        drivers.forEach(driver -> {
            int days = VehicleUtil.getDriverValidPeriodDays(driver.getRegister());
            if (days == 30 || days == 7) {
                accordSize.getAndIncrement();
                StringBuffer content = new StringBuffer();
                Reply reply = DriverInfoServer.getDriverInfo(driver);
                Driver d1 = (Driver) reply.getData();
                if (d1 != null) {
                    vehicleService.updateDriverScore(driver.getId(), d1.getScore(), driver.getCode());
                    driver = vehicleService.getDriver(driver);
                    content.append(VehicleUtil.getDriverInfo(driver));
                    List<String> memberNums = vehicleService.findDriverMem(driver.getId());
                    memberNums.forEach(memberNum -> {
                        Vehicle v = new Vehicle();
                        List<Vehicle> vehicles = vehicleService.findVehicle(memberNum);
                        vehicles.forEach(vehicle -> {
                            v.setWzSize(v.getWzSize() + vehicle.getWzSize());
                            v.setWzMoney(v.getWzMoney() + vehicle.getWzMoney());
                            v.setWzFen(v.getWzFen() + vehicle.getWzFen());
                        });
                        content.append(VehicleUtil.getVehicleInfo(v));
                        remindVehicleService.businessRemind(memberNum, new String[]{"驾照分数清零提醒" + "\n", content.toString(),
                                "数据存在延迟，仅供参考"});
                        pushSize.getAndIncrement();
                    });
                }
            }
        });
        params.put("pushSize", String.valueOf(pushSize.get()));
        params.put("accordSize", String.valueOf(accordSize.get()));
        return params;
    }


    /**
     * 推送即将需要年检的车辆信息
     *
     * @return
     */
    @Scheduled(cron = "0 0 9 * * ?")
    public Map<String, Object> vehiclePeriodRemind() {
        AtomicInteger pushSize = new AtomicInteger();
        AtomicInteger accordSize = new AtomicInteger();
        logger.info("定时任务【每天早上9点检查是否存在90天或30天或7天可能需年检的车辆】触发");
        List<Vehicle> vehicles = vehicleService.findVehicle(null);
        Date date = new Date();
        vehicles.forEach(vehicle -> {
            String url = MenuEnum.BTN_DRIVER_LINK.getUrl() + "?plate=" + vehicle.getPlate();
            url = WxUtil.transferWxUrl(url, MenuEnum.BTN_DRIVER_LINK.getKey(), baseUrl);

            Date nearTime = VehicleUtil.vehicleInspection(vehicle.getRegister());
            vehicleService.updateVehicleInspectTime(vehicle, nearTime);
            int days = DateUtil.daysBetween(date, nearTime);
            if (days == 90 || days == 30 || days == 7) {
                accordSize.getAndIncrement();
                StringBuffer content = new StringBuffer();
                content.append(VehicleUtil.getVehicleInfo(vehicle, nearTime, days));
                List<String> memberNums = vehicleService.findVehicleMem(vehicle.getId());
                String finalUrl = url;
                memberNums.forEach(memberNum -> {
                    remindVehicleService.businessRemind(memberNum, new String[]{"车辆年检提醒" + "\n", content.toString(), "数据存在延迟，仅供参考"}, finalUrl);
                    pushSize.getAndIncrement();
                });
            }
        });
        params.put("pushSize", String.valueOf(pushSize.get()));
        params.put("accordSize", String.valueOf(accordSize.get()));
        return params;
    }


    /**
     * 每3个月查询驾驶证分数是否改变，改变则推送
     *
     * @return 推送次数
     */
    @Scheduled(cron = "0 0 9 1,3,6,9 * ?")
    public Map<String, Object> driverFenUpdate() {
        logger.info("定时任务【每3个月查询驾驶证分数】手动触发");
        AtomicInteger pushSize = new AtomicInteger();
        AtomicInteger accordSize = new AtomicInteger();
        List<Driver> drivers = vehicleService.findDriver(null);
        drivers.forEach(driver -> {
            accordSize.getAndIncrement();
            Reply reply = DriverInfoServer.getDriverInfo(driver);
            Driver d1 = (Driver) reply.getData();
            if (d1 != null) {
                vehicleService.updateDriverScore(driver.getId(), d1.getScore(), reply.getCode());
                int score = d1.getScore() - driver.getScore();
                if (score != 0) {
                    vehicleService.updateDriverScore(driver.getId(), d1.getScore(), reply.getCode());
                    List<String> memberNums = vehicleService.findVehicleMem(driver.getId());
                    StringBuffer content = new StringBuffer();
                    content.append("您的驾驶证在近三个月内扣除").append(score).append("分").append("还剩").append(12 - d1.getScore()).append("分");
                    memberNums.forEach(memberNum -> {
                        remindVehicleService.businessRemind(memberNum, new String[]{"驾驶证分数改变" + "\n", content.toString(), "数据存在延迟，仅供参考"});
                        pushSize.getAndIncrement();
                    });
                }
            }
        });
        params.put("pushSize", String.valueOf(pushSize.get()));
        params.put("accordSize", String.valueOf(accordSize.get()));
        return params;
    }
}
